<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/22
 * Time: 10:26
 */

defined('BASEPATH') OR exit('No direct script access allowed');

class Shopify_api
{
    
    public $web_name = '';
    
    public $web_access = '';
    
    public $ab_name = '';
    
    public $web_id = '';
    
    public function __construct($params = array())
    {
        
        $this->initialize($params);
        log_message('info', 'Pagination Class Initialized');
    }

    /**
     * 初始化
     * @param array $params
     *
     * @return $this
     * initialize
     * author: walker
     * Date: 2019/12/5
     * Time: 10:55
     * Note:
     */
    public function initialize($params = array())
    {
        $this->web_name = $params['web_name'];
        $this->web_access = $params['web_access'];
        $this->ab_name = $params['ab_name'];
        $this->web_id = $params['web_id'];
        return $this;
    }

    /**
     * 产品统计
     *
     * @param int $down_time
     *
     * @return array|bool
     * products_count
     * author: walker
     * Date: 2019/12/5
     * Time: 10:55
     * Note:
     */
    public function products_count($down_time = 0)
    {
        $t = time();
        
        $today = strtotime('today') - 3600*12;
        
        $start = date('Y-m-d\TH:i:s-04:00', $down_time ? ($down_time -  3600*12 - 60*20) : (strtotime('2017-10-01') - 3600*12));
        $end = date('Y-m-d\TH:i:s-04:00', $today + 3600*24);
        $limit = 50;
        
        $url = $this->web_access . '.myshopify.com/admin/products/count.json?created_at_min='.$start. '&created_at_max=' . $end. '&published_status=any';
        $data = $this->shopify_curl($url);
        $count = $data['count'];
        
        if ($count > 0) {
            $max = $limit;
            $page_max  = ceil($count / $max);
            $arr = array();
            for ($i=1; $i<=$page_max; $i++) {
                $arr[] = array(
                    'shopify_url' => 'published_status=any&page=' .$i. '&created_at_min='.$start.'&created_at_max=' . $end. '&limit='.$max,
                    'add_time' => $t,
                    'web_id' => $this->web_id,
                    'type' => 0
                );
            }
            
            return array_reverse($arr);
            
        } else {
            return false;
        }
    }
    /**
     * 商品数据
     */
    public function products_data($params_url)
    {
        $url = $this->web_access . '.myshopify.com/admin/products.json?' . $params_url;
        $data = $this->shopify_curl($url);
        
        if ($data['products']) {
            $cont = $data['products'];
        } else {
            $cont = false;
        }
        
        return $cont;
    }
    /**
     * 订单统计
     */
    public function order_count($down_time = 0)
    {
        $t = time();
        
        $today = strtotime('today') - 3600*12;
        
        $start = date('Y-m-d\TH:i:s-04:00', $down_time ? ($down_time -  3600*12 - 60*80) : (strtotime('2018-3-10') - 3600*12));
        $end = date('Y-m-d\TH:i:s-04:00', $today + 3600*24);
        $limit = 100;
        $url = $this->web_access . '.myshopify.com/admin/orders/count.json?updated_at_min='.$start. '&updated_at_max=' . $end. '&status=any';
        $count = file_get_contents($url);
        $count = json_decode($count,true);
        $count = $count['count'];
        if ($count > 0) {
            $max = $limit;
            $page_max  = ceil($count / $max);
            
            //循环每页的数据
            $arr = array();
            for ($i=1; $i<=$page_max; $i++) {
                $arr[] = array(
                    'shopify_url' => 'status=any&page=' .$i. '&updated_at_min='.$start.'&updated_at_max=' . $end. '&limit='.$max,
                    'add_time' => $t,
                    'web_id' => $this->web_id,
                    'type' => 0
                );
            }
            return array_reverse($arr);
            
        } else {
            return false;
        }
    }
    
    /*public function order_count($down_time = 0)
    {
        $t = time();

        $today = strtotime('today') - 3600*12;

        $start = date('Y-m-d\TH:i:s-05:00', $down_time ? ($down_time -  3600*12) : (strtotime('2017-10-01') - 3600*12));
        $end = date('Y-m-d\TH:i:s-05:00', $today + 3600*24);
        $limit = 86;

        $url = $this->web_access . '.myshopify.com/admin/orders/count.json?created_at_min='.$start. '&created_at_max=' . $end. '&financial_status=paid&status=any';
        $count = file_get_contents($url);
        $count = json_decode($count,true);
        $count = $count['count'];
        if ($count > 0) {
            $max = $limit;
            $page_max  = ceil($count / $max);

            //循环每页的数据
            $arr = array();
            for ($i=1; $i<=$page_max; $i++) {
                $arr[] = array(
                    'shopify_url' => 'financial_status=paid&status=any&page=' .$i. '&created_at_max='.$start.'&created_at_max=' . $end. '&limit='.$max,
                    'add_time' => $t,
                    'web_id' => $this->web_id,
                    'type' => 0
                );
            }

            return array_reverse($arr);

        } else {
            return false;
        }
    }*/
    /**
     * 订单数据
     */
    public function order_data($params_url)
    {
        $url = $this->web_access . '.myshopify.com/admin/orders.json?' . $params_url;

        $data = $this->shopify_curl($url);
        if (!$data['errors']) {
            $cont = $data['orders'];
        } else {
            $cont = false;
        }

        return $cont;
    }

    /**
     *
     * @param $shopify_id
     *
     * @return bool
     * order_payment_no
     * author: walker
     * Date: 2019/12/5
     * Time: 14:29
     * Note:
     */
    public function order_payment_no($shopify_id)
    {
        $url = $this->web_access . ".myshopify.com/admin/orders/{$shopify_id}/transactions.json";
        
        $data = $this->shopify_curl($url);
        if ($data['transactions']) {
            foreach ($data['transactions'] as $row) {
                if ($row['status'] == 'success') {
                    return $row;
                }
            }
        }
        
        return false;
    }
    public function order_upload_shipping_no($shopify_id, $order)
    {
        if ($this->web_id == 2) {
            $location_id = 5983862844;
        } elseif ($this->web_id == 1) {
            $location_id = 1634795550;
        } elseif ($this->web_id == 3) {
            $location_id = 10609524793;
        } elseif ($this->web_id == 4) {
            $location_id = 18461392963;
        } elseif ($this->web_id == 5) {
            $location_id = 19967311985;
        } elseif ($this->web_id == 6) {
            $location_id = 19472416868;
        }
        
        $url = $this->web_access . ".myshopify.com/admin/orders/{$shopify_id}/fulfillments.json";
        
        $fulfillment = array(
            'fulfillment' => array(
                'location_id' => $location_id,
                'tracking_number' => $order['shipping_no'],
                'tracking_url' => $order['shipping_url'],
                'tracking_company' => 'Other',
                'notify_customer' => true
            )
        );
        $data = $this->shopify_curl($url, $fulfillment);
        
        if ($data) {
            return $data['fulfillment'];
        }
        
        return false;
    }

    public function get_variants($shopify_id)
    {
        $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}/variants.json";
        $data = $this->shopify_curl($url, array(), 'GET');

        return $data;
    }

    public function update_variants($shopify_id, $arr_data)
    {
        $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}.json";

        $variants = array(
            "product" => array(
                'id' => $shopify_id,
                'variants' => $arr_data
            )
        );

        $data = $this->shopify_curl($url, $variants, 'PUT');

        return $data;
    }

    public function upload_goods($data)
    {
        $url = $this->web_access . ".myshopify.com/admin/products.json";

        $product = array(
            'product' => array (
                'vendor' => $this->web_name,
                'title' => $data['goods_name'],
                'body_html' => $data['body_html'],
                'tags' => $data['tags'],
                'variants' => $data['variants'],
                'images' => $data['images'],
                'options' => $data['options'],
                'published' => false
            )
        );
        
        $data = $this->shopify_curl($url, $product);

        if ($data) {
            return $data['product'];
        }
        
        return false;
    }

    public function baby_upload_goods($data)
    {
        $url = $this->web_access . ".myshopify.com/admin/products.json";

        $product = array(
            'product' => array (
                'vendor' => $this->web_name,
                'title' => $data['baby_goods_name'],
                'body_html' => $data['baby_body_html'],
                'variants' => $data['variants'],
                'images' => $data['images'],
                'options' => $data['options'],
                'published' => false
            )
        );
        $data = $this->shopify_curl($url, $product);
        if ($data) {
            return $data['product'];
        }
        
        return false;
    }

    public function shopify_sku_img($product_id,$image_id,$res = []){
        $url = $this->web_access . ".myshopify.com/admin/products/{$product_id}/images/{$image_id}.json";
        $data = $this->shopify_curl($url, $res, 'PUT');

        return $data;
    }

    public function published_goods($shopify_id, $is_show = false)
    {
        $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}.json";
        $product = array(
            'product' => array(
                'id' => $shopify_id,
                'published' => $is_show
            )
        );

        $data = $this->shopify_curl($url, $product, 'PUT');

        return $data;
    }

    public function goods_delete($shopify_id){
        $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}.json";
        $data = $this->shopify_curl($url,'', 'DELETE');
        return $data;
    }

    public function published_sku($shopify_id, $variants)
    {
        $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}.json";

        $var = array();
        foreach ($variants as $v) {
            $var[] = array(
                'option1' => $v['option1'],
                'option2' => $v['option2'],
                'sku' => $v['sku'],
                'price' => $v['price'],
                'inventory_quantity' => 9999,
                "fulfillment_service" => "manual",
                'inventory_management' => 'shopify'
            );
        }

        $product = array(
            'product' => array(
                'id' => $shopify_id,
                'variants' => $var
            )
        );

        $data = $this->shopify_curl($url, $product, 'PUT');

        return $data;
    }
    //更新sku 带数量
    public function published_up_sku($shopify_id, $variants)
    {
        $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}.json";
        $product = array(
            'product' => array(
                'id' => $shopify_id,
                'variants' => $variants
            )
        );

        $data = $this->shopify_curl($url, $product, 'PUT');

        return $data;
    }



    public function published_status_sales($product_id,$val){
        $url = $this->web_access . ".myshopify.com/admin/products/{$product_id}.json";
        //$val 2 是false
        if($val == 2){
            $product = ['product'=>['id'=>$shopify_id,'published'=>false]];
        }else{
            $product = ['product'=>['id'=>$shopify_id,'published'=>true]];
        }
        
        $data = $this->shopify_curl($url, $product, 'PUT');
    }

    public function update_up_goods($data,$is = '')
    {
        $url = $this->web_access . ".myshopify.com/admin/products/{$data['shopify_id']}.json";

        $var = array();
        foreach ($data['variants'] as $v) {
            $var[] = array(
                'option1' => $v['option1'],
                'option2' => $v['option2'],
                'sku' => $v['sku'],
                'price' => $v['price'],
                'inventory_quantity' => 9999,
                "fulfillment_service" => "manual",
                'inventory_management' => 'shopify',
                //'compare_at_price' => $data['compare_at_price']
            );
        }

        $product = array(
            'product' => array(
                'title' => $data['goods_name'],
                'body_html' => $data['body_html'],
                //'tags' => $data['tags'],
                'variants' => $var,
                'images' => $data['images'],
                'published' => $data['is_sales'] ? true : false
            )
        );

//        if(!$is){
//            $this->update_img($data['shopify_id'],$data['images'],$data['cunzai']);
//        }
        
        $data = $this->shopify_curl($url, $product, 'PUT');

        if ($data) {
            return $data['product'];
        }
        
        return false;
    }

    //只更新图片
    public function update_up_goods_img($data){
        $url = $this->web_access . ".myshopify.com/admin/products/{$data['shopify_id']}.json";
        $product = array(
            'product' => array(
                // "id"=> $data['shopify_id'],
                'images' => $data['images'],
            )
        );
        // print_R($product);die;
        $data = $this->shopify_curl($url, $product, 'PUT');
        return $data;
// print_R($data);die;
    }

    //修改图片
    public function update_img($shopify_id,$images,$cunzai){
        //goods表shopify_id不存在就删图片
        if($cunzai == 0){
            //获取这个商品在Shopify图片ID
            $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}/images.json";
            $data = $this->shopify_curl($url,null, 'GET');
            if(!empty($data['images'])){
                //删除所有图片
                foreach($data['images'] as $k => $v){
                    $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}/images/{$v['id']}.json";
                    $this->shopify_curl($url,[], 'DELETE');
                }
            }
            
        }
        
        //上传图片
        foreach ($images as $k => $v) {
            $url = $this->web_access . ".myshopify.com/admin/products/{$shopify_id}/images.json";
            $image['image'] = $v;
            $this->shopify_curl($url,$image, 'POST');
        }


    }
    
    // public function aa(){
    //     $url = $this->web_access . ".myshopify.com/admin/api/2019-10/customers/count.json";
    //     // $url = $this->web_access . ".myshopify.com/admin/api/2019-07/customers.json?page=549";
    //     $data = $this->shopify_curl($url, array(), 'GET');
    //     return $data['count'];
    // }
    // public function shopify_user_add($page){
    //     $url = $this->web_access . ".myshopify.com/admin/api/2019-07/customers.json?page=".$page;
    //     $data = $this->shopify_curl($url, array(), 'GET');
    //     return $data;
    // }
    
    public function shopify_user_add($created_at_min,$created_at_max){
        
        $url = $this->web_access . '.myshopify.com/admin/api/2019-07/customers.json?limit=250&created_at_min='.$created_at_min.'&created_at_max='.$created_at_max;
        $arr = $this->shopify_curl($url,array(), 'GET');
        return $arr;
    }
    
    public function up_shopify_goods_cat($data){
        $url = $this->web_access . '.myshopify.com/admin/api/2019-10/smart_collections.json';
        $arr = $this->shopify_curl($url,$data, 'POST');
        return $arr;
    }

    public function shopify_goods_list($since_id){
        if(empty($since_id)){
            $url = $this->web_access . '.myshopify.com/admin/api/2019-10/products.json';
        }else{
            $url = $this->web_access . '.myshopify.com/admin/api/2019-10/products.json?'.$since_id;
        }
        $arr = $this->shopify_her_curl($url,[], 'GET');
        return $arr;
    }

    public function shopify_page(){
        $url = $this->web_access . '.myshopify.com/admin/api/2019-10/products/count.json';
        $arr = $this->shopify_curl($url,[], 'GET');
        return $arr;
    }
    public function shopify_curl($url, $post_data = array(), $method = 'POST')
    {
        // j_write_log($url, 'shopify');
        // j_write_log($post_data, 'shopify');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        
        if ($post_data || $method == 'DELETE') {
            $data_string = json_encode($post_data);
            
            $headers = array(
                "Content-Type: application/json",
                "Accept: application/json",
                "Content-Length:" . strlen($data_string)
            );
            
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        
        $content = curl_exec($ch);
        // j_write_log($content, 'shopify');

        curl_close($ch);
        
        return json_decode($content, true);
    }



    public function shopify_her_curl($url, $post_data = array(), $method = 'POST')
    {
        j_write_log($url, 'shopify');
        j_write_log($post_data, 'shopify');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        
        if ($post_data || $method == 'DELETE') {
            $data_string = json_encode($post_data);
            
            $headers = array(
                "Content-Type: application/json",
                "Accept: application/json",
                "Content-Length:" . strlen($data_string)
            );
            
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        $response = curl_exec($ch);
        if(curl_getinfo($ch,CURLINFO_HTTP_CODE) == 200 ){
            $headerSize = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
            $header = substr($response,0,$headerSize);
            $border = substr($response,$headerSize);
        }
        curl_close($ch);
        $len = stripos($header,">") - stripos($header,"page_info=");
        $page = substr($header,stripos($header,"page_info="),$len);
        $border=json_decode($border,true);
        $border['page'] = $page;
        return $border;
    }
}

